package com.cctc.juc.demo.Bitc.Tmp.ADemo;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class HCyclicBarrierRunDemo {

    // 效果 7： 等待 A、B、C 全部准备就绪后，再各自继续向下执行。

    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
    private static Random random = new Random();

    public static void main(String[] args) {
        for (char ch = 'A'; ch <= 'C'; ch++) {
            final String threadName = String.valueOf(ch);
            new Thread(() -> {
                long preTime = random.nextInt(5000);
                System.out.println(threadName + " -> 准备时间: " + preTime);
                try {
                    Thread.sleep(preTime);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(threadName + " -> 已经准备好了，等待其他线程就绪...");
                try {
                    cyclicBarrier.await();
                } catch (BrokenBarrierException | InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(threadName + "-> 开始执行...");
            }).start();
        }
    }

}
